class Listener {
    _registrys = {};
    constructor(ks = []) {
        for (const key of ks)
            this.listen(key);
    }
    listen(type, callback, once = false) {
        const ks = Array.isArray(type) ? type : [type];
        if (callback) {
            for (const type of ks) {
                if (!this._registrys[type])
                    this._registrys[type] = [];
                const row = this._registrys[type].find((r) => r.callback === callback);
                if (row)
                    continue;
                this._registrys[type].push({ once: once ?? false, callback });
            }
        }
        else {
            for (const type of ks) {
                if (!this._registrys[type])
                    this._registrys[type] = [];
            }
        }
    }
    unlisten(type, callback) {
        if (!this._registrys[type])
            return;
        for (let i = 0; i < this._registrys[type].length; i++) {
            if (this._registrys[type][i].callback !== callback)
                continue;
            this._registrys[type].splice(i, 1);
            return;
        }
    }
    trigger(type, e) {
        if (!this._registrys[type])
            throw `无法触发该事件 ${type}`;
        if (this._registrys[type].length === 0)
            return;
        const registry = [...this._registrys[type]];
        for (let i = 0; i < registry.length; i++) {
            registry[i].callback(e);
            if (registry[i].once === true)
                this.unlisten(type, registry[i].callback);
        }
    }
}

const listener = new Listener(['/home', '/fire', '/info'])

export { listener }
